//
//  XYDownloadController.swift
//  XYReadBook
//
//  Created by fox on 2017/10/24.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit
let IdentifierDownload = "XYDownloadControllerIdentifier"
/// 下载 想到了可以用数组,来存所有章节的url 后面只需要一个去重就可以搞定一切
class XYDownloadController: XYViewController {
    var chapterCount:Int = 50
    var selectedArr:[String] = []   // 记录多选
    var openArr:[String] = [] // 记录展开状态
    var chapterCountIndex:Int = 0 // 记录了选择了多少章节
    var chapters:[Int:String] = Dictionary<Int,String>()  
    let bookModel:XYReadModel

    var modelArr:[[Chapters]] = []
    var dataArr:[Chapters] = []

    var headerSelectedDict:[Int:Int] = Dictionary<Int,Int>()
    var footView:XYDownloadFootView = XYDownloadFootView()

     typealias Task = () -> Void
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var tableView:UITableView = {
        let tableView = UITableView.init(frame: CGRect.zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.register(XYDownloadCell.self, forCellReuseIdentifier:IdentifierDownload)

        tableView.register(XYDownloadHeadView.self, forHeaderFooterViewReuseIdentifier: "XYDownloadHeadView")
        return tableView
    }()

    deinit {
        XYLog(messsage: "人心何至如此冷也")
    }

    init(bookModel:XYReadModel) {
        self.bookModel = bookModel
        super.init(nibName: nil, bundle: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if HTTPManager.isnetWorkBool() == false {
            let errorView = XYErrorView.init(frame: self.view.bounds, errorType: .errorNotWork)
            view.addSubview(errorView)

            errorView.overrideLoadData = {
                XYLog(messsage: "重新加载网络数据")
            }
        }else {
            setupUI()
        }
    }

    func setupUI() {
        navigationItem.title = "下载"
        // 大循环 从0 到章节count
        for index in 0...bookModel.chapters.count - 1{
            // 把单个模型 放进数组
            // 需求,每50章放进一个数组
            // 那么怎么判定是50章呢? 100 ,150 ?
            // 证明不是五十的倍数
            let chapterModel = bookModel.chapters[index] // 章节模型
            dataArr.append(chapterModel)
            if (index + 1) % 50 == 0 {
                // 证明就是50的倍数
                // 在创建一个数组,再此循环
                modelArr.append(dataArr) // 大集合
                dataArr.removeAll()
            }
            if index == bookModel.chapters.count - 1 {
                 modelArr.append(dataArr) // 大集合
                 dataArr.removeAll()
            }
        }
        let result = ceil(Double(bookModel.chapters.count) / Double(chapterCount));
        XYLog(messsage: result)
        // 操作两个数必须是相同类型
        let num = Int(result)
        for _ in 0...num {
            openArr.append("0")
            selectedArr.append("0")
        }
        view.addSubview(tableView)
        view.addSubview(footView)

        footView.clickDownLoad = { chapterCount,downloadBtn in

          self.view.showActivity()
            DispatchQueue.global().async {
                runDownload()
            }

            func runDownload() {

                let keys = self.headerSelectedDict.values
                let arr = self.chapters.keys.sorted()

                func getKey(index: Int) -> String{
                    let curentLink = self.chapters[index]?.urlEncode
                    if curentLink != nil {
                        let urlKey = BaseUrl.chapter.rawValue + curentLink!
                        return urlKey
                    }
                    return ""
                }
                for index in 0...arr.count - 1 {
                    let urlKey = getKey(index:arr[index])
                    HTTPManager.requestModel(url: urlKey, method: .get, parameters: nil, iscaChe: true) {[weak self] (resp:XYChapterTextModel?, error) in
                        if error != nil {
                            XYLog(messsage: "下载👻👻")
                        }
                        if index == arr.count - 1 {
                            MBProgressHUD.wj_hide()
                            DispatchQueue.main.async(execute: {
                                self?.view.dimissActivity()
                                self?.chapters.removeAll()
                                self?.footView.chapterCount = 0
                                for key in (self?.headerSelectedDict)! {
                                    let headerView = self?.tableView.headerView(forSection: key.value) as?XYDownloadHeadView
                                    headerView!.isEndDownloadlab = true
                                }
                                MBProgressHUD.wj_showSuccess(withColouredRibbonAnimation: "下载成功", hideAfterDelay: 2.0)
                            })
                        }
                    }
                }
            }
        }
    }


    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        var footViewH = 58
        if footView.chapterCount > 0 {
            footViewH = 100
        }else {
            footViewH = 58
        }
        tableView.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight - CGFloat(footViewH))
        footView.frame = CGRect.init(x: 0, y:tableView.frame.maxY , width:ScreenWidth , height: CGFloat(footViewH))
    }

    func delay(_ time: TimeInterval, _ method: @escaping Task) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time, execute: method)
    }
}


extension XYDownloadController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        // 每五十章即算为一个组 bug
        let result = ceil(Double(bookModel.chapters.count) / Double(chapterCount));
        // 操作两个数必须是相同类型
        let num = Int(result)
        return num
    }


    // 处理最后一组
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if openArr[section] == "1" {
            if section == modelArr.count - 1{
                // 是最后一组
                let chapCount = (bookModel.chapters.count) % 50
                // 问题往往就是发生自己认为写的没问题的地方 fuck
                  return chapCount
            }else {
                 return chapterCount
            }

        }else {
            return 0
        }
    }

    // 处理最后一组
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: IdentifierDownload, for: indexPath)as!XYDownloadCell
        cell.model = modelArr[indexPath.section][indexPath.row]
        let isSection = indexPath.section

        if self.selectedArr[isSection] == "1" {
           cell.isSelectedBtn = true
        }else {
           cell.isSelectedBtn = false
        }
        let chapterIndex = (indexPath.section * 50) + indexPath.row
        let contains = self.chapters[chapterIndex]
        if contains != nil {
            cell.isSelectedBtn = true
        }

        weak var weakSelf = self
        cell.selectedChapter = { chapterBtn in

            if chapterBtn.isSelected == true {
             let chapterIndex = (indexPath.section * 50) + indexPath.row
                weakSelf?.chapters[chapterIndex] = weakSelf?.bookModel.chapters[chapterIndex].link
            }else {

                let chapterIndex = (indexPath.section * 50) + indexPath.row
                weakSelf?.chapters.removeValue(forKey: chapterIndex)
            }

            //if (count = 已经下载章节数 + 选中的count) < 50 章
            let starIndex = indexPath.section * 50
            var count = starIndex + 50
            // 这里还需要处理最后一章的问题
            if indexPath.section == self.modelArr.count - 1{
                XYLog(messsage: "最后一章")
                let chapCount = (self.bookModel.chapters.count) % 50
                count = count + chapCount - 50
            }
            var downloadFalg = 0 // 当前组被下载过的数量
            for index in starIndex...count - 1 {
                let curentLink = self.bookModel.chapters[index].link.urlEncode!
                let urlKey = BaseUrl.chapter.rawValue + curentLink
                let iscontains = HTTPCache.xwj_containsObject(forKey: urlKey)
                if iscontains == true {
                    downloadFalg += 1
                }
            }

            XYLog(messsage: starIndex)
            XYLog(messsage: count)

            var keyFlag = 0
            // 取出所有的key并且排序
            let arr = [Int](self.chapters.keys).sorted()

            // 在计算出当期的起始 下标
            for index in 0...arr.count - 1 {
                let key = arr[index]
                if key >= starIndex && key <= count - 1{
                    keyFlag += 1
                }
            }
  
            if keyFlag + downloadFalg > self.modelArr[indexPath.section].count - 1 {
                let headerView = tableView.headerView(forSection: indexPath.section) as!XYDownloadHeadView
                headerView.isSelected = true
            }else {
                let headerView = tableView.headerView(forSection: indexPath.section) as!XYDownloadHeadView
                headerView.isSelected = false
            }

            weakSelf?.footView.chapterCount = self.chapters.count
            weakSelf?.view.setNeedsLayout()
        }
        return cell
    }


    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }


    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        tableView.deselectRow(at: indexPath, animated: true)

    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let header = XYDownloadHeadView.init(reuseIdentifier: "XYDownloadHeadView")
        header.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 40)
        header.backgroundColor = UIColor.white
        header.selectedBtn.tag = section
        let binIndex = (section * chapterCount) + 1
        var result = section * chapterCount + chapterCount
        // 判断是否是最后一组
        if section == modelArr.count - 1{
            // 是最后一组
             let chapCount = (bookModel.chapters.count) % 50
            result = (((section ) * chapterCount) + chapCount) + 1
        }

        header.chapters = modelArr[section]
        header.chapterText = String.init(format: "第%zd章 - 第%zd章",binIndex,result);
        /// MARK - 让Cell全选

        weak var weakSelf = self
        weak var weakHeader = header

        // MARK -- 在这里判断有Cell已经下载过的.如果已经有下载过.那么就不选择50章了
        header.selected = { btn in
            weakHeader?.isSelected = !header.isSelected
             let starIndex = section * 50
              var count = starIndex + 50

            // 这里还需要处理最后一章的问题
            if section == self.modelArr.count - 1{
                XYLog(messsage: "最后一章")
                let chapCount = (self.bookModel.chapters.count) % 50
                count = count + chapCount - 50
            }

            // 遍历cell
            for index in 0...49 {
                let newIndexPath = IndexPath.init(row: index, section: section)
                let cell = tableView.cellForRow(at: newIndexPath)as?XYDownloadCell
                cell?.isSelectedBtn = weakHeader?.isSelected
            }


            if weakSelf?.selectedArr[section] == "1" {
                weakSelf?.headerSelectedDict.removeValue(forKey: section)
                XYLog(messsage: "取消")
                XYLog(messsage: weakSelf?.headerSelectedDict.count)
                weakSelf?.selectedArr[section] = "0"
                for index in starIndex...count - 1 {
                    let curentLink = self.bookModel.chapters[index].link.urlEncode!
                    let urlKey = BaseUrl.chapter.rawValue + curentLink
                    let iscontains = HTTPCache.xwj_containsObject(forKey: urlKey)
                    if iscontains == false {
                       self.chapters.removeValue(forKey: index)
                    }
                }

            }else {

                // 字典增加
                weakSelf?.headerSelectedDict.updateValue(section, forKey: section)
                 XYLog(messsage: "选中")
                XYLog(messsage:   weakSelf?.headerSelectedDict.count)
                weakSelf?.selectedArr[section] = "1"
                for index in starIndex...count - 1{

                    let curentLink = self.bookModel.chapters[index].link.urlEncode!
                    let urlKey = BaseUrl.chapter.rawValue + curentLink
                    let iscontains = HTTPCache.xwj_containsObject(forKey: urlKey)
                    if iscontains == false {
                      self.chapters[index] = weakSelf?.bookModel.chapters[index].link
                    }
                }
            }

            weakSelf?.footView.chapterCount = self.chapters.count
            self.view.setNeedsLayout()
        }
//
        if self.openArr[section] == "1" {
            // 让其header展开
            header.isUpImageView = true
            XYLog(messsage: "展开")
        }

        if self.selectedArr[section] == "1" {
            header.isSelected = true
        }

        header.selectedChapter = { chapterBtn in
              XYLog(messsage: "章节")
            if weakSelf?.openArr[section] == "1" {
                weakSelf?.openArr[section] = "0"
            }else {
                weakSelf?.openArr[section] = "1"
            }

            tableView.reloadSections(IndexSet.init(integer: section), with: .automatic)

        }
        return header
    }
}


